package cn.blunce.utils.AsyncTaskHelper;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import cn.blunce.mylib.R;

public class AsyncTaskTest extends Activity {

    private static final int PROGRESS = 0x01;
    private ProgressBar progressBar;
    private TextView showProgress;
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case PROGRESS:
                    progressBar.setProgress(msg.arg1 * 10);
                    showProgress.setText(msg.arg1 * 10 + "%");
                    break;
                default:
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
//        doWork();
        new ProgressTask().execute("", null, "");
    }

    private void initView() {
        setContentView(R.layout.activity_main);
        progressBar = (ProgressBar) findViewById(R.id.progress_show);
        showProgress = (TextView) findViewById(R.id.progress_show_status);
    }

    private void doWork() {
        new Thread() {
            public void run() {
                for (int i = 0; i <= 10; i++) {
                    try {
                        sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    mHandler.obtainMessage(PROGRESS, i, 0).sendToTarget();
                }
            }
        }.start();
    }

    /**
     * 暂停半秒
     */
    private void stopHalfSecond() throws InterruptedException {
        Thread.sleep(500);
    }

    private class ProgressTask extends AsyncTask<String, Integer, String> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... params) {
            for (int i = 0; i <= 10; i++) {
                try {
                    stopHalfSecond();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                publishProgress(i);
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            progressBar.setProgress(values[0] * 10);
            showProgress.setText(values[0] * 10 + "%");
        }

        @Override
        protected void onPostExecute(String aVoid) {
            super.onPostExecute(aVoid);
            Toast.makeText(AsyncTaskTest.this, "Done!", Toast.LENGTH_LONG).show();
        }
    }
}
